﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;
using System.Threading;
using WatiN.Core.Interfaces;
using WatiN.Core.Mozilla;

namespace WatiNCF.Extensions
{
    public static class BrowserExtensions
    {
        /// <summary>
        /// Waits for async post back to complete.
        /// </summary>
        /// <param name="ie">The ie instance to use.</param>
        public static void WaitForAsyncPostBackToComplete(this IBrowser ie)
        {
            switch (ie.BrowserType)
            {
                case BrowserType.InternetExplorer:
                    {
                        bool isInPostback = true;
                        while (isInPostback)
                        {
                            isInPostback = Convert.ToBoolean(ie.Eval("Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack();"));
                            if (isInPostback)
                            {
                                Thread.Sleep(200); //sleep for 200ms and query again 
                            }
                        }
                        break;
                    }
            }
        }

        public static void CaptureWebPageToFile(this IBrowser browser, string fileName)
        {
            switch(browser.BrowserType)
            {
                case BrowserType.InternetExplorer:
                    {
                        ((IE)browser).CaptureWebPageToFile(fileName);
                        break;
                    }
            }
        }

        public static void Close(this IBrowser browser)
        {
            switch (browser.BrowserType)
            {
                case BrowserType.InternetExplorer:
                    {
                        ((IE)browser).Close();
                        break;
                    }
                case BrowserType.FireFox:
                    {
                        break;
                    }
            }
        }
    }
}
